<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script>
    //获取元素是否在可视区域
    function isElementInViewport(el) {
      var rect = el.getBoundingClientRect();
      return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <=
        (window.innerHeight || document.documentElement.clientHeight) &&
        rect.right <=
        (window.innerWidth || document.documentElement.clientWidth)
      );
    }

    function checkImg() {
      let imgs = document.querySelectorAll("img[lazy]");
      Array.from(imgs).forEach(ele => {
        if (isElementInViewport(ele)) {
          loadImg(ele)
        }
      })
    }

    function loadImg(el) {
      if (!el.src) {
        let source = el.dataset.src;
        el.src = source;
      }
    }

    addEventListener('scroll', function () {

      var img = document.getElementsByTagName('img')[0];
      let rs = isElementInViewport(img);
      if(rs){
        loadImg(img);
      }

    })


  </script>
</head>

<body>

  <p>1</p>
  <p>1</p>
  <p>1</p>
  <p>1</p>
  <p>1</p>
  <p>1</p>
  <p>1</p>
  <p>1</p>
  <p>1</p>
  <p>1</p>
  <p>1</p>
  <p>1</p>
  <p>1</p>
  <p>1</p>
  <p>1</p>
  <p>1</p>
  <p>1</p>
  <p>1</p>
  <p>1</p>
  <p>1</p>
  <p>1</p>
  <p>1</p>
  <p>1</p>
  <p>1</p>
  <p>1</p>
  <p>1</p>
  <p>1</p>
  <p>1</p>
  <p>1</p>

  <img data-src="./images/1.png"  lazy>

</body>

</html>